<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-my.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-my.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-my.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="javascript,ajax,">





  <link rel="alternate" href="/atom.xml" title="徐子玉的笔记" type="application/atom+xml">






<meta name="description" content="Ajax前端相关的技术点 html 主要用来实现页面的排版布局 css 主要用来实现页面的样式美化 javaScript 主要用来实现前端功能特效   采用上面的这些技术开发的页面和前端特效脚本需要放到服务器才能够对外提供服务，才能够让互联网上的网友看到。">
<meta name="keywords" content="javascript,ajax">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax原理">
<meta property="og:url" content="http://blog.xuziyu.cn/Ajax原理.html">
<meta property="og:site_name" content="徐子玉的笔记">
<meta property="og:description" content="Ajax前端相关的技术点 html 主要用来实现页面的排版布局 css 主要用来实现页面的样式美化 javaScript 主要用来实现前端功能特效   采用上面的这些技术开发的页面和前端特效脚本需要放到服务器才能够对外提供服务，才能够让互联网上的网友看到。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-03-16T07:34:33.685Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Ajax原理">
<meta name="twitter:description" content="Ajax前端相关的技术点 html 主要用来实现页面的排版布局 css 主要用来实现页面的样式美化 javaScript 主要用来实现前端功能特效   采用上面的这些技术开发的页面和前端特效脚本需要放到服务器才能够对外提供服务，才能够让互联网上的网友看到。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"always","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xuziyu.cn/Ajax原理.html">






  <title>Ajax原理 | 徐子玉的笔记</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b49e4132be4caecace2fcc27c6e8ec4d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/knight-peter" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">徐子玉的笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Good Good Stady, Day Day Up.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xuziyu.cn/Ajax原理.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="徐子玉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="徐子玉的笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Ajax原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-13T16:55:00+08:00">
                2018-02-13
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/前端/" itemprop="url" rel="index">
                    <span itemprop="name">前端</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/Ajax原理.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="Ajax原理.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye" style="margin-right:7px;"></i>阅读次数
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,143 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12 分钟
                </span>
              
            </div>
          

          

        </span></div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h1><h2 id="前端相关的技术点"><a href="#前端相关的技术点" class="headerlink" title="前端相关的技术点"></a>前端相关的技术点</h2><ul>
<li>html 主要用来实现页面的排版布局</li>
<li>css 主要用来实现页面的样式美化</li>
<li>javaScript 主要用来实现前端功能特效</li>
</ul>
<blockquote>
<p>采用上面的这些技术开发的页面和前端特效脚本需要放到服务器才能够对外提供服务，才能够让互联网上的网友看到。<br><a id="more"></a></p>
</blockquote>
<h2 id="客户端与服务器"><a href="#客户端与服务器" class="headerlink" title="客户端与服务器"></a>客户端与服务器</h2><blockquote>
<p>本质上都是计算机，只不过样子不同，配置不同，应用场景不同（安装的应用软件不同） </p>
</blockquote>
<ul>
<li>客户端主要用于普通上网用户</li>
<li>服务器主要给上网用户提供后台服务</li>
</ul>
<h2 id="网络相关概念"><a href="#网络相关概念" class="headerlink" title="网络相关概念"></a>网络相关概念</h2><ul>
<li>IP地址（唯一的确定互联网上的一台计算机）</li>
<li>域名 IP地址的别名，方便记忆</li>
<li>DNS 用于维护IP地址与域名的关系</li>
<li>端口 用来确定计算机上的网络应用程序</li>
</ul>
<h2 id="通信协议理解"><a href="#通信协议理解" class="headerlink" title="通信协议理解"></a>通信协议理解</h2><blockquote>
<p>通信双方约定的规则</p>
</blockquote>
<ul>
<li>http/https 超为本传输协议</li>
<li>ftp 文件传输协议</li>
<li>smpt/pop3 邮件收发协议</li>
<li>……</li>
</ul>
<h2 id="网站"><a href="#网站" class="headerlink" title="网站"></a>网站</h2><blockquote>
<p>网站由一系列页面组成（页面由js、css、图片、html标签。。。所有的这些文件都被称为资源）</p>
</blockquote>
<h3 id="静态网站"><a href="#静态网站" class="headerlink" title="静态网站"></a>静态网站</h3><blockquote>
<p>就是提前写好的html页面（包括图片、媒体文件。。。静态资源文件），并且部署到服务器上</p>
</blockquote>
<ul>
<li>静态网站主要存在的问题：<ul>
<li>随着网站规模的增大可维护性逐渐降低</li>
<li>没有交互性</li>
</ul>
</li>
</ul>
<h3 id="动态网站"><a href="#动态网站" class="headerlink" title="动态网站"></a>动态网站</h3><blockquote>
<p>动态指的是html页面是动态生成的，这里动态生成的不一定是一个完整的页面，有可能仅仅是页面的一部分，或者仅仅是数据(普通字符串、json、xml)</p>
</blockquote>
<ul>
<li><p>实现动态网站的技术：</p>
<ul>
<li>php</li>
<li>java（jsp）</li>
<li>.net</li>
<li>Node.js</li>
<li>python</li>
<li><p>……</p>
<h3 id="http-协议"><a href="#http-协议" class="headerlink" title="http 协议"></a>http 协议</h3><p>get       |     用来获取数据<br>post      |     用来添加数据<br>put       |     用来修改数据<br>delete    |     用来删除数据</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p>http 协议的常用请求方式: <strong>增删改查</strong></p>
</blockquote>
<h2 id="PHP基础语法"><a href="#PHP基础语法" class="headerlink" title="PHP基础语法"></a>PHP基础语法</h2><pre><code>&lt;?php PHP的所有语法都写在这个地方 ?&gt;
</code></pre><ul>
<li>PHP文件文件格式是 <code>xxx.php</code>;</li>
</ul>
<h3 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h3><blockquote>
<p>变量以$开头 字母/数字/下划线 不能以数字开头，大小写敏感。</p>
</blockquote>
<h3 id="字符串拼接"><a href="#字符串拼接" class="headerlink" title="字符串拼接"></a>字符串拼接</h3><blockquote>
<p>PHP中字符串拼接用” <strong>.</strong> “;</p>
</blockquote>
<h3 id="单引号"><a href="#单引号" class="headerlink" title="单引号"></a>单引号</h3><blockquote>
<p>PHP中的单引号把包含在其中的变量当作为普通的字符串来处理;</p>
</blockquote>
<h3 id="双引号"><a href="#双引号" class="headerlink" title="双引号"></a>双引号</h3><blockquote>
<p>PHP中的双引号把包含在其中的变量当作变量解析成变量值;</p>
</blockquote>
<h3 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h3><blockquote>
<p>与javaScript基本类似;</p>
</blockquote>
<h3 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h3><ul>
<li>字符串</li>
<li>整型</li>
<li>浮点型</li>
<li>布尔型</li>
<li>数组</li>
<li>对象</li>
<li>NULL<blockquote>
<p>gettype: 是内置数据类型的判断</p>
</blockquote>
</li>
</ul>
<h3 id="输出内容"><a href="#输出内容" class="headerlink" title="输出内容"></a>输出内容</h3><ul>
<li><strong>echo:</strong> 输出简单数据类型, 如字符串, 数值;</li>
<li><strong>print_r():</strong> 输出复杂数据类型, 如数组;</li>
<li><strong>var_dump</strong> 输出详细信息, 如对象, 数组;</li>
</ul>
<h3 id="分之循环"><a href="#分之循环" class="headerlink" title="分之循环"></a>分之循环</h3><ul>
<li>if/switch</li>
<li>while</li>
<li>for<ul>
<li>count()内置函数, 计算数组的长度;</li>
</ul>
</li>
<li>foreach<ul>
<li>foreach($arr as $key =&gt; $value){ };</li>
</ul>
</li>
</ul>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><ul>
<li><strong>自定义函数</strong><ul>
<li>语法类似与JavaScript的自定义函数;</li>
</ul>
</li>
<li><strong>系统函数</strong><ul>
<li>直接调用, 不需要声明;</li>
<li><code>json_encode();</code> 将数组和对象转换为字符串的方法;<h3 id="预定义变量"><a href="#预定义变量" class="headerlink" title="预定义变量"></a>预定义变量</h3></li>
</ul>
</li>
<li><strong>$_GET</strong><ul>
<li>$_GET请求参数获取</li>
<li>$_GET是专门用来接数据用的一个全局数组;</li>
<li>form 默认请求方式就是get请求, get请求会把表单数据作为url的参数进行提交;</li>
</ul>
</li>
<li><p><strong>$_POST</strong></p>
<ul>
<li>$_POST请求参数获取</li>
<li><p>设置服务响应的文件类型:</p>
<ol>
<li>header(“Content-Type: text/plain; charset=utf-8”);</li>
<li>header(“Content-Type: text/html; charset=utf-8”);</li>
</ol>
</li>
<li><p>$_POST也是PHP内置好的专门用来接数据用的一个全局数组;</p>
</li>
</ul>
</li>
<li><p><strong>GET与POST请求方式的差异</strong></p>
</li>
</ul>
<ol>
<li>GET没有请求主体, 使用<code>xhr.send(null)</code>;</li>
<li>GET可以通过在请求URL上添加请求参数;</li>
<li>POST有请求主体, 可以通过;<code>xhr.send(name=itcast=&amp;age=10)</code>;</li>
<li>POST需要设置请求头;</li>
<li>GET效率更好(应用多);</li>
<li>GET大小限制约4K, POST则没有限制;</li>
<li>与 POST 相比, GET 个更简单也更快,并且在大部分情况下都能用。</li>
<li>然而，在以下情况中，使用 POST 请求：<ul>
<li>无法使用缓存文件。</li>
<li>向服务器发送大量数据（POST 没有数据量限制）</li>
<li>发送包含位置字符的用户输入时，POST 比 GET 更稳定也更可靠。</li>
</ul>
</li>
</ol>
<h3 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h3><blockquote>
<p>HTML</p>
</blockquote>
<pre><code>&lt;div&gt;
    &lt;form action=&quot;./page6-data.php&quot; method=&quot;post&quot;&gt;
        考号：&lt;input type=&quot;text&quot; name=&quot;code&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;查询&quot;&gt;
    &lt;/form&gt;
&lt;/div&gt;
</code></pre><blockquote>
<p>PHP 文件名:page6-data.php</p>
</blockquote>
<pre><code>&lt;?php 
    / 服务器端渲染页面
    arr = array();
    arr[&apos;123&apos;] = array(&quot;username&quot;=&gt;&quot;张三&quot;,&quot;chinese&quot;=&gt;&quot;130&quot;,&quot;math&quot;=&gt;&quot;149&quot;,&quot;english&quot;=&gt;&quot;146&quot;,&quot;summary&quot;=&gt;&quot;298&quot;);
    arr[&apos;124&apos;] = array(&quot;username&quot;=&gt;&quot;李四&quot;,&quot;chinese&quot;=&gt;&quot;100&quot;,&quot;math&quot;=&gt;&quot;140&quot;,&quot;english&quot;=&gt;&quot;136&quot;,&quot;summary&quot;=&gt;&quot;298&quot;);
    arr[&apos;125&apos;] = array(&quot;username&quot;=&gt;&quot;王五&quot;,&quot;chinese&quot;=&gt;&quot;90&quot;,&quot;math&quot;=&gt;&quot;139&quot;,&quot;english&quot;=&gt;&quot;126&quot;,&quot;summary&quot;=&gt;&quot;298&quot;);
    arr[&apos;126&apos;] = array(&quot;username&quot;=&gt;&quot;赵六&quot;,&quot;chinese&quot;=&gt;&quot;30&quot;,&quot;math&quot;=&gt;&quot;50&quot;,&quot;english&quot;=&gt;&quot;80&quot;,&quot;summary&quot;=&gt;&quot;100&quot;);
    code = $_POST[&apos;code&apos;];
    f($code == &apos;admin&apos;){
        foreach($arr as $value){
            echo &quot;&lt;ul&gt;
                &lt;li&gt;姓名：$value[username]&lt;/li&gt;
                &lt;li&gt;语文：$value[chinese]&lt;/li&gt;
                &lt;li&gt;数学：$value[math]&lt;/li&gt;
                &lt;li&gt;英语：$value[english]&lt;/li&gt;
                &lt;li&gt;综合：$value[summary]&lt;/li&gt;
            &lt;/ul&gt;&quot;;
       }
    else{
        $score = $arr[$code];
        echo &quot;&lt;ul&gt;
            &lt;li&gt;姓名：$score[username]&lt;/li&gt;
            &lt;li&gt;语文：$score[chinese]&lt;/li&gt;
            &lt;li&gt;数学：$score[math]&lt;/li&gt;
            &lt;li&gt;英语：$score[english]&lt;/li&gt;
            &lt;li&gt;综合：$score[summary]&lt;/li&gt;
        &lt;/ul&gt;&quot;;
    }
?&gt;
</code></pre><h3 id="后台接口"><a href="#后台接口" class="headerlink" title="后台接口"></a>后台接口</h3><ol>
<li>将数组和对象转换为字符串的方法 — json_encode();</li>
<li>将字符串转换为对象的方式 — json_decod();</li>
<li>接口说白了就是后台返回特定格式数据, 而不是一个完整的页面, 就是从后台到前台返回一些数据;</li>
</ol>
<h3 id="请求参数分析"><a href="#请求参数分析" class="headerlink" title="请求参数分析"></a>请求参数分析</h3><blockquote>
<p> <strong>open();</strong></p>
</blockquote>
<pre><code>xhr.open(&quot;get&quot;,&quot;nemo.php?username=&quot;+uname+&quot;&amp;password=&quot;+pwd,true);
</code></pre><ul>
<li>调用open方法并不会真正发送请求, 而是启动一个请求以备发送.</li>
<li>它接受三个参数: <ul>
<li>参数一: 请求方式(get获取数据, post提交数据);</li>
<li>参数二: 请求地址;</li>
<li>参数三: 同步或者异步标识位, 默认是 true, true表示异步, false 表示同步;</li>
</ul>
</li>
<li><strong>注意：</strong> 如果是get请求， 那么请求参数必须在url中传递， 那么就用<code>encodeURI（）</code> 进行编码，防止乱码。</li>
</ul>
<blockquote>
<p><strong>send();</strong></p>
</blockquote>
<ul>
<li>如果要发送请求， 用send()方法。</li>
<li>要发送特定的请求，需要调用send（）方法。它接收一个参数，即要作为请求主体发送的数据。</li>
<li>get请求，则必须传入null。post请求传入字符串。</li>
<li>get请求是只有头部，没有主体的，而post请求有请求主体。</li>
<li><strong>注意：</strong>post请求参数通过send传递，不需要通过<code>encodeURI()</code>转码,但是必须需要设置请求参数.</li>
</ul>
<h3 id="创建-xhr-对象"><a href="#创建-xhr-对象" class="headerlink" title="创建 xhr  对象"></a>创建 xhr  对象</h3><pre><code>1. 标准: xhr = new XMLHttprequest();
2. IE6: xhr = newActiveXObject(&apos;Microsoft.XMLHTTP&quot;);
</code></pre><ul>
<li>xhr 对象有一个重要的属性, 就是 readyState 属性,表示”就绪状态”, 就是 <code>xhr.readyState</code>。</li>
<li><p>readyState 取值有5种值： 0、1、2、3、4</p>
<pre><code>0  -----  未初始化。
1  -----  XMLHttpRequest对象正在加载。
2  -----  xmlHttp对象加载完毕。
3  -----  正在传输数据。
4  -----  全部完成。
</code></pre></li>
<li><p>只要 readyState改变后，就会触发一个事件 <code>onreadystatechange</code> 事件.</p>
<pre><code>xhr.onreadyStatechange = function(){};
</code></pre></li>
<li><p>Ajax-但用senp方法发出HTTP请求之后,判断ceadyState得到的时候,就会有一个属性<code>xhr.status</code>表示的是请求的文件的状态码.</p>
<pre><code>1. 1**  -----   消息.
2. 200  -----   代码请求成功.
3. 3**  -----   重定向.
4. 404  -----   请求错误.
5. 500  -----   服务器错误.
6. 6**  -----   其他.
</code></pre></li>
</ul>
<h3 id="案例-1"><a href="#案例-1" class="headerlink" title="案例"></a>案例</h3><blockquote>
<p>HTML</p>
</blockquote>
<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;
    window.onload = function(){
        var btn = document.getElementById(&apos;btn&apos;);
        btn.onclick = function(){
            var uname = document.getElementById(&apos;username&apos;).value;
            var pw = document.getElementById(&apos;password&apos;).value;
            // 1、创建XMLHttpRequest对象
            var xhr = null;
            if(window.XMLHttpRequest){
                xhr = new XMLHttpRequest();//标准
            }else{
                xhr = new ActiveXObject(&quot;Microsoft&quot;);//IE6
            }
            // 2、准备发送
            /*
                参数一：请求方式（get获取数据；post提交数据）
                参数二：请求地址
                参数三：同步或者异步标志位，默认是true表示异步，false表示同步            
                post请求参数通过send传递，不需要通过encodeURI()转码
                必须设置请求头信息
            */
            var param = &apos;username=&apos;+uname+&apos;&amp;password=&apos;+pw;
            ------------------------------------------------
            get方法:
            xhr.open(&apos;get&apos;,&apos;03get.php?&apos;+encodeURI(param),true); 
            // 3、执行发送动作                                 
            xhr.send(null);//get请求这里需要添加null参数  
            ------------------------------------------------
            post方法:
            xhr.open(&apos;post&apos;,&apos;04post.php&apos;,false);
            // 3、执行发送动作
            xhr.setRequestHeader(&quot;Content-Type&quot;,&quot;application/x-www-form-urlencoded&quot;);
            xhr.send(param);//post请求参数在这里传递，并且不需要转码
            ------------------------------------------------
            // 4、指定回调函数
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                        var data = xhr.responseText;
                        var info = document.getElementById(&apos;info&apos;);
                    if(data == &apos;1&apos;){
                        info.innerHTML = &apos;登录成功&apos;;
                    }else if(data == &apos;2&apos;){
                        info.innerHTML = &apos;用户名或者密码错误&apos;;
                    }
                }
            }
        }
    }
&lt;/script&gt;

&lt;body&gt;
    &lt;form&gt;
        用户名：&lt;input type=&quot;text&quot; name=&quot;username&quot; id=&quot;username&quot;&gt;
        &lt;span id=&quot;info&quot;&gt;&lt;/span&gt;
        &lt;br&gt; 
        密码：&lt;input type=&quot;text&quot; name=&quot;password&quot; id=&quot;password&quot;&gt;
        &lt;input type=&quot;button&quot; value=&quot;登录&quot; id=&quot;btn&quot;&gt;
    &lt;/form&gt;
&lt;/body&gt;
</code></pre><blockquote>
<p>PHP</p>
</blockquote>
<pre><code>&lt;?php
    ----------------------------
    $_GET方法:
    $uname = $_GET[&apos;username&apos;];
    $pw = $_GET[&apos;password&apos;];
    ----------------------------
    $_POST方法:
    $uname = $_POST[&apos;username&apos;];
    $pw = $_POST[&apos;password&apos;];
    ----------------------------
    if($uname == &apos;admin&apos; &amp;&amp; $pw == &apos;123&apos;){
        echo 1;
    }else{
        echo $uname;
    }
?&gt;
</code></pre><h2 id="XML"><a href="#XML" class="headerlink" title="XML"></a>XML</h2><h3 id="XML-数据格式"><a href="#XML-数据格式" class="headerlink" title="XML 数据格式"></a>XML 数据格式</h3><h4 id="什么是-XML"><a href="#什么是-XML" class="headerlink" title="什么是 XML"></a>什么是 XML</h4><ul>
<li>XML 指可扩展的标记语言</li>
<li>主要用来输出和存储数据<ul>
<li>设置宗旨是(传输数据)，而非显示数据</li>
</ul>
</li>
<li>XML 标签没有语义化，需要自行定义标签</li>
</ul>
<h4 id="XML-数据格式的缺点"><a href="#XML-数据格式的缺点" class="headerlink" title="XML 数据格式的缺点"></a>XML 数据格式的缺点</h4><ul>
<li>原数据占用的数据量比较大，不利于大量数据的网络传输</li>
<li>解析不太方便</li>
</ul>
<h4 id="XML-和-HTML-的区别"><a href="#XML-和-HTML-的区别" class="headerlink" title="XML 和 HTML 的区别"></a>XML 和 HTML 的区别</h4><ul>
<li>XML 是用来传输和存储数据的，而HTML被设计是用来显示数据的</li>
<li>XML 只在传输数据,HTML 只在显示信息</li>
</ul>
<h4 id="XML-的树结构"><a href="#XML-的树结构" class="headerlink" title="XML 的树结构"></a>XML 的树结构</h4><ul>
<li>XML 文档行程了的也是一种”树结构”</li>
<li><strong>XML文档必须包含根元素</strong>. 该元素是所有其他元素的父元素, 树结构从根开始,扩展到最低端</li>
</ul>
<h4 id="XML-的语法"><a href="#XML-的语法" class="headerlink" title="XML 的语法"></a>XML 的语法</h4><ul>
<li>所有 XML 元素都必须是闭合标签</li>
<li>XML 标签大小写明感,因此必须使用相同的大小写来编写打开标签和关闭标签</li>
<li>XML 必须正确的嵌套</li>
<li>XML 文档必须有根元素</li>
<li>XML 的属性值必须加引号</li>
<li>在 XML 中,空格会被保留</li>
</ul>
<h2 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h2><h3 id="json-数据结构"><a href="#json-数据结构" class="headerlink" title="json 数据结构"></a>json 数据结构</h3><h4 id="什么是-JSON"><a href="#什么是-JSON" class="headerlink" title="什么是 JSON"></a>什么是 JSON</h4><ul>
<li>JavaScript 对象表示法</li>
<li>是存储和交换文本信息的语法</li>
<li>轻量级的文本数据交换格式</li>
</ul>
<h4 id="JSON-数据和普通数据的-JS-兑现的区别"><a href="#JSON-数据和普通数据的-JS-兑现的区别" class="headerlink" title="JSON 数据和普通数据的 JS 兑现的区别"></a>JSON 数据和普通数据的 JS 兑现的区别</h4><ul>
<li>json 对象没有变量</li>
<li>json 形式的数据结尾没有分号</li>
<li>json 数据中的键必须用双引号包括</li>
</ul>
<h4 id="JSON-和-XML-对比"><a href="#JSON-和-XML-对比" class="headerlink" title="JSON 和 XML 对比"></a>JSON 和 XML 对比</h4><ul>
<li>JSON 比 XML 更小, 更快, 更易解析</li>
</ul>
<h3 id="json-数据解析"><a href="#json-数据解析" class="headerlink" title="json 数据解析"></a>json 数据解析</h3><ul>
<li><p>把 json 文本转换为 JavaScript 对象</p>
<blockquote>
<p>JSON 最常见的用法之一, 是从 Web 服务器上读取 JSON 数据(作为文件或作为HttpRequest), 将 JSON 数据转换为 JavaScript 对象, 然后在网页中使用该数据.</p>
</blockquote>
</li>
<li><p>为什么要转换</p>
<blockquote>
<p>在数据传输过程中, json 是以文本, 即字符串的形式传递的, 而 JS 操作的是 JSON 对象. 所以, JSON 对象和 JSON 字符串之间的相互转换是关键.</p>
</blockquote>
</li>
<li><p>转换的方法</p>
<ul>
<li><code>JSON_parse();</code> 把 json 形式的字符串转成对象</li>
<li><code>JSON_stringify();</code> 把对象转成字符串</li>
<li><code>eval()</code> 把字符串解析成 js 代码并执行</li>
</ul>
</li>
</ul>
<h3 id="JSON-数据接口"><a href="#JSON-数据接口" class="headerlink" title="JSON 数据接口"></a>JSON 数据接口</h3><ul>
<li><code>json_encode();</code> 把数组转换成 JSON 形式的字符串</li>
</ul>
<h3 id="同步与异步"><a href="#同步与异步" class="headerlink" title="同步与异步"></a>同步与异步</h3><ul>
<li>同步<ul>
<li>重新加载页面</li>
<li>彼此等待</li>
</ul>
</li>
<li><p>异步</p>
<ul>
<li>局部加载页面</li>
<li>各做各的</li>
</ul>
</li>
<li><p>面试题：为什么JavaScript是单线程的却能让AJAX异步发送和回调请求</p>
<blockquote>
<p>JS运行在浏览器中，是单线程的，每个window一个JS线程，既然是单线程的，在某个特定的时刻只有特定的代码能够被执行，并阻塞其它的代码。而浏览器是事件驱动的（Event driven），浏览器中很多行为是异步（Asynchronized）的，会创建事件并放入执行队列中。javascript引擎是单线程处理它的任务队列，你可以理解成就是普通函数和回调函数构成的队列。当异步事件发生时，如mouse click, a timer firing, or an XMLHttpRequest completing（鼠标点击事件发生、定时器触发事件发生、XMLHttpRequest完成回调触发等），将他们放入执行队列，等待当前代码执行完成。</p>
</blockquote>
</li>
</ul>
<h2 id="Ajax跨域"><a href="#Ajax跨域" class="headerlink" title="Ajax跨域"></a>Ajax跨域</h2><ul>
<li><p>什么是跨域</p>
<blockquote>
<p>跨域是指从一个域名的网页去请求另一个域名的资源。只要 <strong>协议</strong>、<strong>域名</strong>、<strong>端口</strong>有任何一个的不同，就被当作是跨域。</p>
</blockquote>
</li>
<li><p>跨域解决方案</p>
<ul>
<li>jsonp,</li>
<li>document.domain + iframe,</li>
<li>location.hash + iframe,</li>
<li>window.name + iframe,</li>
<li>window.postMessage,</li>
<li><p>flash 等第三方方插件.</p>
<blockquote>
<p>大部分都是使用 jsonp.</p>
</blockquote>
</li>
</ul>
</li>
</ul>
<h3 id="JSONP-原理"><a href="#JSONP-原理" class="headerlink" title="JSONP 原理"></a>JSONP 原理</h3><ul>
<li><p>静态 script 标签的 src 实现跨域</p>
<ul>
<li>script标签里面的 async 属性表示异步加载资源, 默认是同步加载.</li>
</ul>
</li>
<li><p>动态创建 script 标签发出去的请求是异步请求.</p>
</li>
</ul>
<h3 id="jQuery-基本使用-ajax"><a href="#jQuery-基本使用-ajax" class="headerlink" title="jQuery 基本使用 ($.ajax)"></a>jQuery 基本使用 ($.ajax)</h3><pre><code>$.ajax({
    url: &apos;地址&apos;,
    type: &apos;请求数据方法 ( get post )&apos;,
    dataType: &apos;返回的数据类型 (json jsonp )&apos;,
    data: {后台接受的数据 : 获取某个数据},
    jsonpCallback:&apos;为jsonp请求指定一个回调函数名&apos;
})
 success:function(返回的数据){
    请求成功后的回调函数;
 };
</code></pre>
      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="徐子玉 wechat" style="width: 200px; max-width: 100%;">
    <div>欢迎您扫一扫上面的微信二维码，订阅我的公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat-reward.gif" alt="徐子玉 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay-reward.gif" alt="徐子玉 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/javascript/" <i class="fa fa-tag"> javascript</a>
          
            <a href="/tags/ajax/" <i class="fa fa-tag"> ajax</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/vue小白学习笔记0--购物车.html" rel="next" title="vue小白学习笔记0--购物车">
                <i class="fa fa-chevron-left"></i> vue小白学习笔记0--购物车
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/极验证-geetest-前端配置.html" rel="prev" title="极验证-geetest-前端配置">
                极验证-geetest-前端配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="徐子玉">
            
              <p class="site-author-name" itemprop="name">徐子玉</p>
              <p class="site-description motion-element" itemprop="description">喜欢跑步的吃货才是一个好程序猿</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/knight-peter" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:xuqipeter@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.imooc.com" title="慕课网" target="_blank" rel="external nofollow">慕课网</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/" title="廖雪峰的官方网站" target="_blank" rel="external nofollow">廖雪峰的官方网站</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Ajax"><span class="nav-number">1.</span> <span class="nav-text">Ajax</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#前端相关的技术点"><span class="nav-number">1.1.</span> <span class="nav-text">前端相关的技术点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端与服务器"><span class="nav-number">1.2.</span> <span class="nav-text">客户端与服务器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网络相关概念"><span class="nav-number">1.3.</span> <span class="nav-text">网络相关概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通信协议理解"><span class="nav-number">1.4.</span> <span class="nav-text">通信协议理解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#网站"><span class="nav-number">1.5.</span> <span class="nav-text">网站</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#静态网站"><span class="nav-number">1.5.1.</span> <span class="nav-text">静态网站</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#动态网站"><span class="nav-number">1.5.2.</span> <span class="nav-text">动态网站</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#http-协议"><span class="nav-number">1.5.3.</span> <span class="nav-text">http 协议</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PHP基础语法"><span class="nav-number">1.6.</span> <span class="nav-text">PHP基础语法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#变量"><span class="nav-number">1.6.1.</span> <span class="nav-text">变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串拼接"><span class="nav-number">1.6.2.</span> <span class="nav-text">字符串拼接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单引号"><span class="nav-number">1.6.3.</span> <span class="nav-text">单引号</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#双引号"><span class="nav-number">1.6.4.</span> <span class="nav-text">双引号</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运算符"><span class="nav-number">1.6.5.</span> <span class="nav-text">运算符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据类型"><span class="nav-number">1.6.6.</span> <span class="nav-text">数据类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#输出内容"><span class="nav-number">1.6.7.</span> <span class="nav-text">输出内容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分之循环"><span class="nav-number">1.6.8.</span> <span class="nav-text">分之循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数"><span class="nav-number">1.6.9.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#预定义变量"><span class="nav-number">1.6.10.</span> <span class="nav-text">预定义变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案例"><span class="nav-number">1.6.11.</span> <span class="nav-text">案例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#后台接口"><span class="nav-number">1.6.12.</span> <span class="nav-text">后台接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#请求参数分析"><span class="nav-number">1.6.13.</span> <span class="nav-text">请求参数分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建-xhr-对象"><span class="nav-number">1.6.14.</span> <span class="nav-text">创建 xhr  对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案例-1"><span class="nav-number">1.6.15.</span> <span class="nav-text">案例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#XML"><span class="nav-number">1.7.</span> <span class="nav-text">XML</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#XML-数据格式"><span class="nav-number">1.7.1.</span> <span class="nav-text">XML 数据格式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是-XML"><span class="nav-number">1.7.1.1.</span> <span class="nav-text">什么是 XML</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#XML-数据格式的缺点"><span class="nav-number">1.7.1.2.</span> <span class="nav-text">XML 数据格式的缺点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#XML-和-HTML-的区别"><span class="nav-number">1.7.1.3.</span> <span class="nav-text">XML 和 HTML 的区别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#XML-的树结构"><span class="nav-number">1.7.1.4.</span> <span class="nav-text">XML 的树结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#XML-的语法"><span class="nav-number">1.7.1.5.</span> <span class="nav-text">XML 的语法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JSON"><span class="nav-number">1.8.</span> <span class="nav-text">JSON</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#json-数据结构"><span class="nav-number">1.8.1.</span> <span class="nav-text">json 数据结构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是-JSON"><span class="nav-number">1.8.1.1.</span> <span class="nav-text">什么是 JSON</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JSON-数据和普通数据的-JS-兑现的区别"><span class="nav-number">1.8.1.2.</span> <span class="nav-text">JSON 数据和普通数据的 JS 兑现的区别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JSON-和-XML-对比"><span class="nav-number">1.8.1.3.</span> <span class="nav-text">JSON 和 XML 对比</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#json-数据解析"><span class="nav-number">1.8.2.</span> <span class="nav-text">json 数据解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JSON-数据接口"><span class="nav-number">1.8.3.</span> <span class="nav-text">JSON 数据接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#同步与异步"><span class="nav-number">1.8.4.</span> <span class="nav-text">同步与异步</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Ajax跨域"><span class="nav-number">1.9.</span> <span class="nav-text">Ajax跨域</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#JSONP-原理"><span class="nav-number">1.9.1.</span> <span class="nav-text">JSONP 原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#jQuery-基本使用-ajax"><span class="nav-number">1.9.2.</span> <span class="nav-text">jQuery 基本使用 ($.ajax)</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">徐子玉</span>

  
</div>

<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">NexT.Mist</a> v5.1.4</div>

-->

<p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>
        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytsHS66l';
      var conf = 'e2a8af2f881183b9aa2cdfcaa43bf747';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
